<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="课程名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入课程名"></a-input>
            </a-form-model-item>
          </a-col>
             <a-col :span="24">
            <a-form-model-item label="积分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="integral">
              <a-input-number v-model="model.integral" placeholder="请输入积分" :min="1"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="课程分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sorts">
              <a-select
                mode="multiple"
                v-model="model.sorts"
                style="width: 100%"
                placeholder="请选择课程分类"
                @change="handleSortsSelectChange"
              >
                <a-select-option v-for="item in subjectList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="课程封面的地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cover">
              <a-upload
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                action="http://localhost:8080/jeecg-boot/rsfile/rsFile/uploadImg"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
<!--                http://hrtools.stalent.net:27110-->
                <img v-if="model.cover" :src="model.cover" alt="avatar" style="width: 128px;height: 128px;" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="课程简介" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="introduction">
              <a-textarea v-model="model.introduction" rows="4" placeholder="请输入课程简介" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="讲师" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lecturer">
              <a-input v-model="model.lecturer" placeholder="请输入讲师"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="personInCharge">
              <a-select
                mode="multiple"
                v-model="model.personInCharge"
                style="width: 100%"
                placeholder="请选择负责人"
                @change="handleSelectChange"
              >
                <a-select-option v-for="item in users" :key="item.id">
                  {{ item.realname }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="课程级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="level">
              <a-select style="width: 100%" v-model="model.level">
                <a-select-option value="VIP">VIP</a-select-option>
                <a-select-option value="免费">免费</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="课程内容"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="chapterRequestVMList"
            >
              <div v-for="(item2, index2) in model.chapterRequestVMList" :key="index2">
                <div style="display:flex; justify-content:space-between;align-items: center; margin-bottom: 15px;">
                  <!-- 是否为编辑 -->
                  <template v-if="item2.isEdit">
                    <a-input
                      v-model="item2.name"
                      :ref="item2.ids"
                      style="width: 100px;"
                      @blur="chapterEditBlur($event, index2)"
                      placeholder="请输入章节名称"
                    ></a-input>
                  </template>
                  <template v-else>
                    <div style="cursor: pointer;" @click="chapterEdit(index2, item2.ids)">
                      <span>{{ item2.name }}</span
                      ><a-icon type="edit" />
                    </div>
                  </template>

                  <a-icon type="close" style="cursor: pointer;" @click="deleteChapter(index2)" />
                </div>
                <div class="chapterBox">
                  <div
                    style="display:flex; justify-content:space-between;align-items: center;border-bottom: 1px solid #eee;padding: 5px;"
                    v-for="(item3, index3) in item2.csSectionList"
                    :key="index3"
                  >
                    <div style="display:flex;align-items:center;">
                      <a-icon type="unordered-list" style="margin-right: 5px;" />
                      <!-- 小节编辑 -->
                      <template v-if="item3.isEdit">
                        <a-input
                          v-model="item3.name"
                          :ref="item3.ids"
                          style="width: 100px;"
                          @blur="chapterInfoEditBlur($event, index2, index3)"
                          placeholder="请输入章节名称"
                        ></a-input>
                      </template>
                      <template v-else>
                        <div style="cursor: pointer;" @click="chapterInfoEdit(index2, index3, item3.ids)">
                          <span>{{ item3.name }}</span
                          ><a-icon type="edit" />
                        </div>
                      </template>
                    </div>
                    <div style="display:flex;align-items:center;">
                      <template v-if="item3.classify === 1">
                        <a style="padding-right: 10px" @click="openScriptModal(index2, index3)">设置脚本</a>
                      </template>
                      <a style="padding-right: 10px" @click="openSettingModal(index2, index3)">{{
                        handleChapterType(item3.classify)
                      }}</a>
                      <a-icon type="close" style="cursor: pointer;" @click="deleteChapterInfo(index2, index3)" />
                    </div>
                  </div>
                  <div style="padding: 5px;">
                    <a-icon type="form" /> <a style="padding: 5px;" @click="addChapterInfo(index2)">新增小节</a>
                  </div>
                </div>
              </div>
              <div>
                <a-button type="primary" @click="addChapter">添加章节</a-button>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <!-- 设置弹出层 -->
      <a-modal
        title="课程内容设置"
        class="settingModal"
        :visible="modalVisible"
        :width="600"
        centered
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-card
          style="margin-top: 24px"
          :bordered="false"
          :tabList="tabList"
          :activeTabKey="activeTabKey"
          @tabChange="
            key => {
              this.activeTabKey = key
            }
          "
        >
          <!-- 视频 -->
          <div v-if="activeTabKey === '1'">
            <a-form :model="videoModel">
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="视频地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <div style="display: flex; align-items: center;">
                      <a-input v-model="videoModel.content" placeholder="视频地址"> </a-input>
                      <a style="display: inline-block;padding-left: 2em; width: 8em;" @click="openFile('video/mp4')"
                        >选择文件</a
                      >
                    </div>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="文档地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <div style="display: flex; align-items: center;">
                      <a-input v-model="videoModel.documentPath" placeholder="文档地址（可选项）"> </a-input>
                      <a
                        style="display: inline-block;padding-left: 2em; width: 8em;"
                        @click="openFile('application/pdf')"
                        >选择文件</a
                      >
                    </div>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="要求学习时常" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <div style="display: flex; align-items: center;">
                      <a-input v-model="videoModel.requiredStudyTime" placeholder="时常" style="width: 100px;">
                      </a-input>
                      <span style="display: inline-block;padding-left: 1em; width: 6em;">分钟</span>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 文档 -->
          <div v-if="activeTabKey === '2'">
            <a-form :model="doucumentModel">
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="文档地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <div style="display: flex; align-items: center;">
                      <a-input v-model="doucumentModel.documentPath" placeholder="文档地址"> </a-input>
                      <a
                        style="display: inline-block;padding-left: 2em; width: 8em;"
                        @click="openFile('application/pdf')"
                        >选择文件</a
                      >
                    </div>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="要求学习时常" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <div style="display: flex; align-items: center;">
                      <a-input v-model="doucumentModel.requiredStudyTime" placeholder="时常" style="width: 100px;">
                      </a-input>
                      <span style="display: inline-block;padding-left: 1em; width: 6em;">分钟</span>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 图文 -->
          <div v-if="activeTabKey === '3'">
            <a-form :model="pictureModel">
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="图文内容" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model="pictureModel.content" placeholder="图文内容"> </a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 试卷 -->
          <div v-if="activeTabKey === '4'">
            <a-form :model="paperModel">
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="选择试卷" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <div style="display: flex; align-items: center;">
                      <a-input v-model="paperModel.content" placeholder="选择试卷"> </a-input>
                      <a style="display: inline-block;padding-left: 2em; width: 8em;" @click="selectPaper">选择试卷</a>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </a-card>
      </a-modal>
      <!-- 试卷弹窗 -->
      <j-modal :visible="paperModalVisible" centered :width="1000" @ok="handlPaperOk" @cancel="handlePaperCancel">
        <div class="title" style="display: flex;align-items: center; margin-bottom: 10px;">
          <span>试卷名称:</span>
          <a-input v-model="paperSearch" placeholder="试卷名称" style="width: 20%;margin: 0 15px; "> </a-input>
          <a-button type="primary" @click="searchByKey">
            查询
          </a-button>
        </div>
        <a-table
          :loading="loading"
          :columns="paperTableConfig"
          :scroll="{ x: 800 }"
          :pagination="pagination"
          :filterMultiple="false"
          :data-source="data"
          :row-selection="rowSelection"
          :expanded-row-keys.sync="expandedRowKeys"
          @change="handlePaperTabaleChange"
        >
        </a-table>
      </j-modal>
      <!-- 文件弹出层 -->
      <fileDialog
        :modalVisible="fileModel"
        :fileType="fileType"
        @ok="fileSelected"
        @cancel="fileSelectedCancel"
      ></fileDialog>
      <!-- 脚本弹出层 -->
      <template v-if="scriptModal">
        <scriptModal
        :scriptModal="scriptModal"
        :videoScriptItems="videoScriptItems"
        :videoSrc="videoSrc"
        @ok="scriptEdit"
        @cancel="scriptEditCancel"
      >
      </scriptModal>
      </template>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getPaperList } from '@/api/oesPaper'
import { httpAction, getAction } from '@/api/manage'
import { getUsers, getSubjects } from '@/api/courseManage'
import { paperTableConfig } from '../tableConfig'
import fileDialog from '@/components/fileDialog'
import scriptModal from '@/components/scriptModal'

import { validateDuplicateValue } from '@/utils/util'
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  name: 'CsCourseForm',
  components: {
    fileDialog,
    scriptModal,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    const rowSelection = {
      onChange: selectedRowKeys => {
        this.selectedRowKeys = selectedRowKeys
      },
      type: 'radio'
    }
    return {
      model: {
        chapterRequestVMList: []
      },
      fileModel: false,
      selectedRowKeys: [],
      fileType: '',
      rowSelection: rowSelection,
      expandedRowKeys: [],
      data: [],
      //脚本弹窗
      scriptModal: false,
      videoSrc: '',
      videoScriptItems: [],
      videoScriptItems2: [],
      //
      videoModel: {
        requiredStudyTime: '',
        documentPath: '',
        content: ''
      },

      doucumentModel: {
        requiredStudyTime: '',
        documentPath: ''
      },
      pictureModel: {
        content: ''
      },
      paperModel: {
        content: ''
      },
      paperTableConfig,
      pageInfo: {
        pageNo: 1,
        pageSize: 10
      },
      pagination: {
        total: 0,
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (current, pageSize) => {
          this.pageInfo.pageSize = pageSize
        }
      },

      paperModalVisible: false,
      paperSearch: '',
      loading: false,
      tabList: [
        {
          key: '1',
          tab: '视频',
          model: 'videoModel'
        },
        {
          key: '2',
          tab: '文档',
          model: 'doucumentModel'
        },
        {
          key: '3',
          tab: '图文',
          model: 'pictureModel'
        },
        {
          key: '4',
          tab: '试卷',
          model: 'paperModel'
        }
      ],
      activeTabKey: '1',
      // 当前编辑的索引
      currentChapterIndex: 0,
      currentChapterInfoIndex: 0,
      chapterIndex: 0,
      modalVisible: false,
      chapterInfoIndex: 0,
      users: [],
      subjectList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/cscourse/csCourse/add',
        edit: '/cscourse/csCourse/add',
        queryById: '/cscourse/csCourse/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  async created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    const res = await getUsers({
      _t: new Date().getTime()
    })
    this.users = res.result.records
    const res2 = await getSubjects({
      _t: new Date().getTime(),
      pageNo: 1,
      pageSize: 9900
    })
    this.subjectList = res2.result.records
  },

  methods: {
    // 脚本弹出层
    scriptEdit() {
      console.log(this.model.chapterRequestVMList[this.currentChapterIndex].csSectionList[this.currentChapterInfoIndex].videoScriptItems,888)
      this.scriptModal = false
    },
    scriptEditCancel() {
      this.model.chapterRequestVMList[this.currentChapterIndex].csSectionList[this.currentChapterInfoIndex].videoScriptItems = this.videoScriptItems2
      this.scriptModal = false
    },
    openScriptModal(index, index2) {
      // 备份一份数据
      this.currentChapterIndex = index
      this.currentChapterInfoIndex = index2
      const item = this.model.chapterRequestVMList[index].csSectionList[index2];
      const item2 = item.videoScriptItems
        ? item.videoScriptItems
        : [];
        this.videoScriptItems2 = []
        item2.forEach(item => {
         this.videoScriptItems2.push({...item})
       })
      this.videoScriptItems = item2
       this.videoSrc = item.content
      // this.ch
      this.scriptModal = true
    },
    // 文件弹出层
    fileSelected(filePath,duration) {
      const item = this.tabList.find(item => item.key === this.activeTabKey)
      if (this.fileType === 'video/mp4') {
        this[item.model].content = filePath
        this[item.model].videoDuration = duration
        console.log(this[item.model])
      } else {
        this[item.model].documentPath = filePath
      }

      this.fileModel = false
    },
    fileSelectedCancel() {
      this.fileModel = false
    },
    openFile(type) {
      this.fileType = type
      this.fileModel = true
    },
    // 试卷弹出层
    async selectPaper() {
      const data = await getPaperList(this.pageInfo)
      this.data = data.result.records.map(item => {
        return {
          key: item.id,
          id: item.id,
          name: item.name
        }
      })
      this.pagination.total = data.result.total
      this.paperModalVisible = true
    },
    handlPaperOk() {
      this.paperModel.content = this.selectedRowKeys[0]
      this.paperModalVisible = false
    },
    handlePaperCancel() {
      this.paperModalVisible = false
    },
    async searchByKey() {
      this.loading = true
      const data = await getPaperList({
        ...this.pageInfo,
        superQueryParams: encodeURI(
          JSON.stringify([{ rule: 'like', type: 'int', dictCode: '', val: this.paperSearch, field: 'name' }])
        )
      })
      this.data = data.result.records.map(item => {
        return {
          key: item.id,
          id: item.id,
          name: item.name
        }
      })
      this.loading = false
    },
    async handlePaperTabaleChange(page) {
      this.loading = true
      this.pageInfo = {
        pageNo: page.current,
        pageSize: page.pageSize
      }
      const data = await getPaperList({
        pageNo: page.current,
        pageSize: page.pageSize
      })
      this.data = data.result.records.map(item => {
        return {
          key: item.id,
          id: item.id,
          name: item.name
        }
      })
      this.loading = false
    },
    // 课程设置弹出层方法
    handleOk() {
      let item = this.model.chapterRequestVMList[this.currentChapterIndex].csSectionList[this.currentChapterInfoIndex]

      const item2 = this.tabList.find(item => item.key === this.activeTabKey)
      this.model.chapterRequestVMList[this.currentChapterIndex].csSectionList[this.currentChapterInfoIndex] = {
        ...item,
        ...this[item2.model],
        classify: Number(this.activeTabKey)
      }
      this.tabList.forEach(item => {
        this[item.model].content = ''
        this[item.model].documentPath = ''
        this[item.model].requiredStudyTime = ''
      })
      this.modalVisible = false
    },
    handleCancel() {
      this.tabList.forEach(item => {
        this[item.model].content = ''
        this[item.model].documentPath = ''
        this[item.model].requiredStudyTime = ''
      })
      this.modalVisible = false
    },
    openSettingModal(index, index2) {
      this.currentChapterIndex = index
      this.currentChapterInfoIndex = index2
      this.modalVisible = true
    },
    // 转化章节类型
    handleChapterType(val) {
      let chapterType = null
      switch (val) {
        case 0:
          chapterType = '设置'
          break
        case 1:
          chapterType = '视频'
          break
        case 2:
          chapterType = '文档'
          break
        case 3:
          chapterType = '图文'
          break
        case 4:
          chapterType = '试卷'
          break
        default:
          chapterType = 'null'
          break
      }
      return chapterType
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }

      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.model.cover = info.file.response.result
        getBase64(info.file.originFileObj, () => {
          this.loading = false
        })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    handleSelectChange(value) {
      this.model.personInCharge = value
    },
    handleSortsSelectChange(value) {
      this.model.sorts = value
    },
    add() {
      console.log(this.modelDefault)
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
    },
    // 章节编辑
    chapterEdit(index, id) {
      this.model.chapterRequestVMList[index].isEdit = true
      this.$nextTick(() => {
        const e = this.$refs[`${id}`]
        e[0].$el.focus()
      })
    },
    chapterEditBlur(e, index) {
      this.model.chapterRequestVMList[index].isEdit = false
    },
    // 小节编辑
    chapterInfoEdit(index2, index3, id) {
      this.model.chapterRequestVMList[index2].csSectionList[index3].isEdit = true
      this.$nextTick(() => {
        const e = this.$refs[`${id}`]
        e[0].$el.focus()
      })
    },
    chapterInfoEditBlur(e, index, index2) {
      this.model.chapterRequestVMList[index].csSectionList[index2].isEdit = false
    },
    // 删除章节
    deleteChapter(index) {
      this.model.chapterRequestVMList.splice(index, 1)
    },
    // 删除小节
    deleteChapterInfo(index, index2) {
      this.model.chapterRequestVMList[index].csSectionList.splice(index2, 1)
    },
    // 新增小节
    addChapterInfo(index) {
      this.model.chapterRequestVMList[index].csSectionList.push({
        name: '',
        isEdit: true,
        ids: this.chapterInfoIndex++,
        id: null,
        classify: 0
      })
    },
    // 新增章节
    addChapter() {
      //
      this.model.chapterRequestVMList.push({
        name: '第' + (this.model.chapterRequestVMList.length + 1) + '章',
        isEdit: false,
        id: null,
        ids: '章节' + this.chapterIndex++,
        csSectionList: [
          {
            name: '',
            isEdit: true,
            id: null,
            ids: '小节' + this.chapterInfoIndex++,
            classify: 0
          }
        ]
      })
    },
    // 表单提交
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          httpAction(
            httpurl,
            {
              ...this.model,
              createUser: JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.id
            },
            method
          )
            .then(res => {
              if (res.success) {
                that.$message.success('操作成功')
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    }
  }
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.anticon-unordered-list svg {
  width: 1.5em;
  height: 1.5em;
}
.settingModal >>> .ant-modal-body {
  padding: 0;
}
.settingModal >>> .ant-card-contain-tabs {
  margin-top: 0 !important;
}
.chapterBox {
  position: relative;
  border-radius: 3px;
  border: 1px solid #ddd;
  background-color: #fff;
  margin-bottom: 15px;
}
</style>
